import os
import numpy as np
import cv2
import json

#从归一化 返原到图中
def get_a_coco_pic():
    pic_path = r"D:\Backup\Downloads\yolov8\ultralytics-main\datasets\bookmak\202307DD1605484033_0.jpg"
    txt_path = r"D:\Backup\Downloads\yolov8\ultralytics-main\datasets\bookmak\202307DD1605484033_0.txt"
    import cv2
    img = cv2.imread(pic_path)
    height, width, _ = img.shape
    print(height, width)

    # cv2.imshow("111",img)
    # 显示原始图片
    # cv2.waitKey()
    # 勾勒多边形
    file_handle = open(txt_path)
    cnt_info = file_handle.readlines()
    new_cnt_info = [line_str.replace("\n", "").split(" ") for line_str in cnt_info]
    print(len(new_cnt_info))
    #print("---====---")
    # 45 bowl 碗 49 橘子 50 西兰花
    color_map = {"41": (0, 255, 255), "45": (255, 0, 255), "50": (255, 255, 0)}
    for new_info in new_cnt_info:
        print('--------------------')
        print(new_info)
        s = []
        for i in range(1, len(new_info), 2):
            b = [float(tmp) for tmp in new_info[i:i + 2]]
            print('--------------------1')
            print(b)
            if(len(b)==2): s.append([int(b[0] * width), int(b[1] * height)])
        print(s)
        cv2.polylines(img, [np.array(s, np.int32)], True, color_map.get(new_info[0]))
    #cv2.imshow('img2', img)
    cv2.imwrite("back.jpg", img)
    cv2.waitKey()

#get_a_coco_pic();

#从百度通用 分割 到归一化
def convert_json_label_to_yolov_seg_label():
    import glob
    import numpy as np
    json_path = r"D:\Backup\Downloads\yolov8\ultralytics-main\datasets\bookmak";
    json_files = glob.glob(json_path + "/*.json")
    for json_file in json_files:
        # if json_file != r"C:\Users\jianming_ge\Desktop\code\handle_dataset\water_street\223.json":
        #     continue
        print(json_file)
        f = open(json_file)
        json_info = json.load(f)
        img_file=json_file.replace('.json', '.jpg')
        print(img_file)
      
        img = cv2.imread(img_file)
        height, width, _ = img.shape
        np_w_h = np.array([[width, height]], np.int32)


        txt_file = json_file.replace(".json", ".txt")
        f = open(txt_file, "a")
        for point_json in json_info["labels"]:
            infotye="0"
            txt_content = ""
            print(point_json["name"])
            print(len(point_json["meta"]))
            if len(point_json["meta"])==0 :
                continue
            if ("points" in point_json["meta"]) :
                print("有")
            else:
                print("没有")
                continue
            print(point_json["meta"]["points"])
            if len(point_json["meta"]["points"])==0 :
                continue
          
            #print(11111)
            print(point_json["meta"]["points"])
            print(22222)
            np_points2 = point_json["meta"]["points"]    #np.array(, np.int32)
            np_points=[]
            for point_json2 in np_points2:
                 #print(point_json2)
                 #print(point_json2["x"])
                 np_points.append([point_json2["x"],point_json2["y"]])
            #print(np_points)
            norm_points = np_points / np_w_h
            norm_points_list = norm_points.tolist()
            txt_content += infotye+" " + " ".join([" ".join([str(cell[0]), str(cell[1])]) for cell in norm_points_list]) + "\n"
            f.write(txt_content)

#convert_json_label_to_yolov_seg_label()

#lambelme  标 转  yolov
def lambelme_json_label_to_yolov_seg_label():
    import glob
    import numpy as np
    json_path = r"D:\Backup\Downloads\yolov8\ultralytics-main\datasets\bookmak";
    json_files = glob.glob(json_path + "/*.json")
    for json_file in json_files:
        # if json_file != r"C:\Users\jianming_ge\Desktop\code\handle_dataset\water_street\223.json":
        #     continue
        print(json_file)
        f = open(json_file)
        json_info = json.load(f)
        # print(json_info.keys())
        #img = cv2.imread(os.path.join(json_path, json_info["imagePath"]))
        height=1440
        width=2560 
        np_w_h = np.array([[width, height]], np.int32)
        txt_file = json_file.replace(".json", ".txt")
        f = open(txt_file, "a")
        for point_json in json_info["shapes"]:
            txt_content = ""
            np_points = np.array(point_json["points"], np.int32)
            norm_points = np_points / np_w_h
            norm_points_list = norm_points.tolist()
            txt_content += "0 " + " ".join([" ".join([str(cell[0]), str(cell[1])]) for cell in norm_points_list]) + "\n"
            f.write(txt_content)

lambelme_json_label_to_yolov_seg_label()
